package io;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FileUtils {
    // 下载超时时间(毫秒)
    private static final int TIMEOUT = 5000;

    // 从URL下载图片并保存到指定路径，支持超时和重名处理
    public static void saveImage(String url, String savePath) throws IOException {
        // 处理文件重名
        String finalPath = getUniqueFilePath(savePath);

        URL imageUrl = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
        conn.setConnectTimeout(TIMEOUT);
        conn.setReadTimeout(TIMEOUT);
        // 设置用户代理，避免部分服务器拒绝请求
        conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)");

        try (InputStream in = new BufferedInputStream(conn.getInputStream());
             FileOutputStream out = new FileOutputStream(finalPath);
             BufferedOutputStream bos = new BufferedOutputStream(out)) {

            byte[] buffer = new byte[1024 * 8]; // 增大缓冲区
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                bos.write(buffer, 0, bytesRead);
            }
        } finally {
            conn.disconnect(); // 确保连接关闭
        }

        // 如果文件名发生了改变，使用新路径记录日志
        appendLog(url, finalPath);
    }

    // 生成不重复的文件路径
    private static String getUniqueFilePath(String originalPath) {
        File file = new File(originalPath);
        if (!file.exists()) {
            return originalPath;
        }

        // 分离文件名和扩展名
        String name = originalPath.substring(0, originalPath.lastIndexOf('.'));
        String ext = originalPath.substring(originalPath.lastIndexOf('.'));

        // 增加计数器直到找到可用文件名
        int counter = 1;
        String newPath;
        do {
            newPath = name + "(" + counter + ")" + ext;
            counter++;
        } while (new File(newPath).exists());

        return newPath;
    }

    // 检查目录是否存在，不存在则创建
    public static void ensureDirectoryExists(String dirPath) {
        if (dirPath == null) { // 新增：避免传入null导致空指针
            return;
        }
        File dir = new File(dirPath);
        if (!dir.exists() && !dir.mkdirs()) {
            throw new RuntimeException("无法创建目录: " + dirPath);
        }
    }

    // 将下载记录追加到日志文件，支持自定义日志路径
    public static void appendLog(String url, String savePath) {
        appendLog(url, savePath, "download_log.txt");
    }

    // 重载方法：指定日志文件路径
    public static void appendLog(String url, String savePath, String logFilePath) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = sdf.format(new Date());
        String log = String.format("%s Downloaded: %s -> %s%n", time, url, savePath);

        try {
            // 修复：处理父目录为null的情况
            File logFile = new File(logFilePath);
            String parentDir = logFile.getParent();
            if (parentDir != null) {  // 只有父目录存在时才创建
                ensureDirectoryExists(parentDir);
            }

            try (FileWriter fw = new FileWriter(logFilePath, true);
                 BufferedWriter bw = new BufferedWriter(fw)) {
                bw.write(log);
            }
        } catch (IOException e) {
            System.out.println("记录日志时发生错误: " + e.getMessage());
        }
    }

    // new: 记录图片重命名日志
    public static void appendRenameLog(String oldName, String newName, String oldPath, String newPath) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = sdf.format(new Date());
        // 日志格式：时间 + 操作类型 + 原信息 + 新信息
        String log = String.format(
                "%s Renamed: 原名称=%s(路径=%s) → 新名称=%s(路径=%s)%n",
                time, oldName, oldPath, newName, newPath
        );

        try {
            File logFile = new File("download_log.txt");
            String parentDir = logFile.getParent();
            if (parentDir != null) {
                ensureDirectoryExists(parentDir);
            }

            try (FileWriter fw = new FileWriter("download_log.txt", true);
                 BufferedWriter bw = new BufferedWriter(fw)) {
                bw.write(log);
            }
        } catch (IOException e) {
            System.out.println("记录重命名日志时发生错误: " + e.getMessage());
        }
    }
}

